using System.Collections;
using UnityEngine;
using BestHTTP.WebSocket;
using System;
using XLua;
using Unity.VisualScripting;

public class WebSocketManager : Singleton<WebSocketManager>
{
    public string address = "ws://8888ws";
    WebSocket webSocket;

    public LuaFunction connectSuccess = null;
    public LuaFunction dataReceive = null;
    public LuaFunction disconnectServer = null;

    private void Start()
    {
        //CreateWebSocket();
    }

    public void CreateWebSocket(string ip = "")
    {
        if (webSocket != null)
        {
            webSocket.Close();
            webSocket = null;
        }

        if (ip != "")
        {
            address = ip;
        }

        try
        {
            webSocket = new WebSocket(new Uri(address));
            InitHandle();
            webSocket.Open();
        }
        catch (Exception e)
        {
            Debug.LogError("websocket err:" + e.Message);
        }

    }

    void InitHandle()
    {
        RemoveHandle();
        webSocket.OnOpen += OnOpen;
        //webSocket.OnMessage += OnMessageReceived;
        webSocket.OnBinary += OnBinaryReceived;
        webSocket.OnClosed += OnClosed;
        webSocket.OnError += OnError;
    }

    void RemoveHandle()
    {
        webSocket.OnOpen -= OnOpen;
        //webSocket.OnMessage -= OnMessageReceived;
        webSocket.OnBinary -= OnBinaryReceived;
        webSocket.OnClosed -= OnClosed;
        webSocket.OnError -= OnError;
    }

    public void BindCallBack(LuaFunction connectSuccess, LuaFunction dataReceive, LuaFunction disconnectServer)
    {
        this.connectSuccess = connectSuccess;
        this.dataReceive = dataReceive;
        this.disconnectServer = disconnectServer;
    }

    void OnOpen(WebSocket ws)
    {
        Debug.Log($"WebSocket Open! state:{ws.State}");
        if (connectSuccess != null)
        {
            connectSuccess.Call();
        }
    }

    void OnMessageReceived(WebSocket ws, string message)
    {
        Debug.Log(message);
    }

    void OnBinaryReceived(WebSocket ws, byte[] data)
    {
        int bytesReceived = data.Length;
        Debug.Log($"Binary received: <color=yellow>{bytesReceived}</color>");
        if (dataReceive != null)
        {
            dataReceive.Call(data);
        }
    }

    void OnClosed(WebSocket ws, UInt16 code, string message)
    {
        Debug.Log(string.Format("WebSocket closed! Code: {0} Message: {1}", code, message));
        webSocket = null;
        if (disconnectServer != null)
        {
            disconnectServer.Call();
        }
    }

    void OnError(WebSocket ws, string error)
    {
        Debug.Log(string.Format("An error occured: <color=red>{0}</color>", error));
        webSocket = null;
        if (disconnectServer != null)
        {
            disconnectServer.Call();
        }
    }

    //向服务端发送信息
    public void Send(int msgId, byte[] buffer)
    {
        Debug.Log($"Send msgId:<color=yellow>{msgId}</color> ,buffer Length: <color=yellow>{buffer.Length}</color> ");
        if (webSocket.IsOpen)
        {
            byte[] bytes = BitConverter.GetBytes(msgId);
            Array.Reverse(bytes);
            byte[] newbytes = new byte[buffer.Length + 4];
            for (int i = 0; i < newbytes.Length; i++)
            {
                if (i < 4)
                {
                    newbytes[i] = bytes[i];
                }
                else
                {
                    newbytes[i] = buffer[i - 4];
                }

            }
            webSocket.Send(newbytes);
        }
    }

}